<template>
  <div class="app-container">
    <el-form  :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="发送用户"  prop="sendUserId">

        <el-select v-model="charUserId" @change = "handleQuery" placeholder="请选择用户" clearable>
          <el-option
            v-for="item in patriarchList"
            :key="item.userId"
            :label="item.nickName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>


    </el-form>



    <div style="background: #F4F5F7;padding: 20px">

      <div  ref="mianscroll" class="chat-msg">

        <div :class="item.sendUserId == userId?'bubble1':'bubble'" v-for="item in chatMsgList">

          <img :src="item.sendAvatar" style="width:45px;border-radius:50%;color: #fff;font-size: 19px;line-height: 20px;margin-right: 15px;margin-left: 15px">
          <div :class="item.sendUserId == userId?'msg-content':'msg-content1'">
            <div>
              {{ item.contents}}
            </div>
            <div style="margin:2px;font-size: 10px;color: #bfbfbf">
              {{item.sendTime}}
            </div>
          </div>
        </div>

        <!--      <div :class="item.sendUserId == userId?'bubble1':'bubble'" v-for="item in chatMsgList">-->
        <!--        <div>-->
        <!--          {{item.sendUserName}}:-->
        <!--        </div>-->
        <!--        <div>-->
        <!--          {{ item.contents}}-->
        <!--        </div>-->
        <!--        <div>-->
        <!--          {{item.sendTime}}-->
        <!--        </div>-->
        <!--      </div>-->


      </div>

      <div class="write" style=" width:1100px;margin-bottom: 40px;margin-top: 20px">

        <div style="width: 700px;margin-right:30px">
          <el-input
            v-model="form.contents"
            placeholder="请输入消息内容"
            clearable
            @keyup.enter.native="sendWebsocketMsg"
            maxlength="50"
            show-word-limit
          />
        </div>
        <el-button type="primary" @click="sendWebsocketMsg"  v-hasPermi="['schoolSys:chatMsg:add']">发送</el-button>

      </div>
    </div>

    <!-- 添加或修改在线咨询对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="发送用户的id" prop="sendUserId">
          <el-input v-model="form.sendUserId" placeholder="请输入发送用户的id" />
        </el-form-item>
        <el-form-item label="接收用户的id" prop="receiveUserId">
          <el-input v-model="form.receiveUserId" placeholder="请输入接收用户的id" />
        </el-form-item>
        <el-form-item label="消息内容" prop="contents">
          <el-input v-model="form.contents" placeholder="请输入消息内容" />
        </el-form-item>
        <el-form-item label="发送时间" prop="sendTime">
          <el-date-picker clearable
            v-model="form.sendTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择发送时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listChatMsg, getChatMsg, delChatMsg, addChatMsg, updateChatMsg, getAllteacher} from "@/api/schoolSys/chatMsg";
import {getAllpatriarch} from "@/api/schoolSys/chatMsg";

export default {
  name: "ChatMsg",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 在线咨询表格数据
      chatMsgList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        // pageNum: 1,
        // pageSize: 10,
        sendUserId: null,
        receiveUserId: null,
        contents: null,
        sendTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      patriarchList:[],
      tokenList:[],
      websocket:null,
      userId:0,
      charUserId:0,
      sendAvatar:""
    };
  },
  created() {
    this.sendAvatar = this.$store.state.user.avatar;
  },
  mounted() {
    this.userId = this.$store.state.user.id;
    // console.log(this.$store.state.user.roles);
    this.getAllchatList();


    this.webSocketConfig();
    this.bottomScrollClick();

  },
  beforeDestroy() {
    websocket.close();
  },
  methods: {
    /** 查询在线咨询列表 */
    getList() {
      this.loading = true;
      listChatMsg(this.queryParams).then(response => {
        this.chatMsgList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.bottomScrollClick();
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sendUserId: null,
        receiveUserId: null,
        contents: null,
        sendTime: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      console.log( this.charUserId)
      this.queryParams.receiveUserId = this.charUserId;
      this.queryParams.sendUserId = this.userId
      console.log(this.queryParams);
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加在线咨询";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getChatMsg(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改在线咨询";
      });
    },
    /** 提交按钮 */
    submitForm() {

          if (this.form.id != null) {
            updateChatMsg(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addChatMsg(this.form).then(response => {
              this.$modal.msgSuccess("发送成功");
              this.open = false;
              // this.getList();

              this.reset();
            });
          }



    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除在线咨询编号为"' + ids + '"的数据项？').then(function() {
        return delChatMsg(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('schoolSys/chatMsg/export', {
        ...this.queryParams
      }, `chatMsg_${new Date().getTime()}.xlsx`)
    },
    /** 查询所有家长 */
    getAllchatList() {
      if(this.$store.state.user.roles[0] == 'admin' || this.$store.state.user.roles[0] == 'teacher' || this.$store.state.user.roles[0] == 'commAdmin'){

        getAllpatriarch().then(response => {
          this.patriarchList = response.data;
          if(this.patriarchList.length>0){
            this.charUserId =this.patriarchList[0].userId;
          }
          this.queryParams.receiveUserId = this.charUserId;
          this.queryParams.sendUserId = this.userId
          this.getList();
        });
      }else if(this.$store.state.user.roles[0] == 'common'){
        getAllteacher().then(response => {
          this.patriarchList = response.data;
          if(this.patriarchList.length>0){
            this.charUserId =this.patriarchList[0].userId;
          }
          this.patriarchList.push({nickName:'管理员',userId:1})
          this.queryParams.receiveUserId = this.charUserId;
          this.queryParams.sendUserId = this.userId
          this.getList();
        });
      }

    },

    bottomScrollClick() {
      this.$nextTick(() => {
        let scrollElem  = this.$refs.mianscroll;

        console.log("scrollElem",scrollElem.scrollHeight)
        scrollElem.scrollTo({ top: scrollElem.scrollHeight, behavior: 'smooth' });
      });
    },
    /**
     配置websocket的参数和回调函数
     */
    webSocketConfig(){
      let that = this;
//判断当前浏览器是否支持WebSocket
      if('WebSocket' in window){
        //连接WebSocket节点
        this.websocket = new WebSocket('ws://localhost:8080/server/'+this.userId);
      }
      else{
        alert('Not support websocket')
      }

      //连接发生错误的回调方法
      this.websocket.onerror = function(){
        console.log("error");
      };

      //连接成功建立的回调方法
      this.websocket.onopen = function(){
        console.log("连接成功");
      }

      //接收到消息的回调方法
      this.websocket.onmessage = function(event){

        console.log(event.data);
        console.log(that.chatMsgList)
        console.log(JSON.parse(event.data))
        that.chatMsgList.push(JSON.parse(event.data));
        that.bottomScrollClick();
      }


      //连接关闭的回调方法
      this.websocket.onclose = function(){
        console.log("close");
      }

    },
    //发送消息
    sendWebsocketMsg(){


      this.form.receiveUserId = this.charUserId;

      // console.log(this.charUserId);
      this.form.sendUserId = this.userId;
      const date = new Date();

// 使用模板字面量和Date对象的方法创建所需格式的字符串
      const formattedDate = `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;

      this.form.sendTime =formattedDate;
      var msg = {};

      msg.receiveUserId = this.charUserId
      msg.sendUserId = this.userId;
      msg.contents = this.form.contents
      msg.sendTime = formattedDate;
      msg.sendUserName = this.$store.state.user.nickName;
      msg.sendAvatar = this.sendAvatar;
      console.log(this.charUserId)
      for(var i = 0; i < this.patriarchList.length; i++){

        // console.log(item);
        if(this.patriarchList[i].userId == this.charUserId){
          msg.receiveUserName = this.patriarchList[i].nickName;
          console.log(this.patriarchList[i].nickName)
        }
      }
      this.websocket.send(JSON.stringify(this.charUserId)+"@"+JSON.stringify(msg));

      this.chatMsgList.push(msg)
      this.bottomScrollClick();
      this.submitForm();
   }
  }
};
</script>
<style>
.chat-msg{
  width: 100%;
  //background: #010199;
  height: 450px;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  //visibility:hidden;
}

.write{
  display: flex;
  flex-display: row;
  justify-content:center;

  position: fixed;
  bottom: 0;

}


.bubble{

  width: 800px;


  margin: 20px 20px 0px 30px;

  height: 45px;
  display: flex;
  flex-direction: row;
  align-content: center;
  justify-content: left;
}
.bubble1{

  width: 800px;


  margin: 20px 20px 0px 30px;

  height: 45px;

  display: flex;
  flex-direction: row-reverse;
  align-content: center;
  justify-content: right;
}
.msg-content{
  background: #C9E7FF;
  border-radius: 20px 0 20px 20px;
  padding: 10px 10px 15px 10px;

}
.msg-content1{
  background: #FFFFFF;
  border-radius:0 20px  20px 20px;
  padding: 10px 10px 15px 10px;

}

</style>

<!--<style>-->

<!--.write{-->
<!--  display: flex;-->
<!--  flex-display: row;-->
<!--  justify-content:center;-->

<!--  position: fixed;-->
<!--  bottom: 0;-->

<!--}-->

<!--.chat-msg{-->
<!--  width: 100%;-->
<!--  //background: #010199;-->
<!--  height: 475px;-->
<!--  display: flex;-->
<!--  flex-direction: column;-->
<!--  overflow-y: auto;-->
<!--  //visibility:hidden;-->
<!--}-->
<!--.bubble{-->

<!--  width: 900px;-->
<!--  background: #FFFFFF;-->
<!--  padding: 15px;-->
<!--  margin: 20px 20px 0px 30px;-->
<!--  border-radius: 20px;-->
<!--  height: 60px;-->
<!--  background: #DCDEE1;-->
<!--  display: flex;-->
<!--  flex-direction: row;-->
<!--  align-content: center;-->
<!--  justify-content: space-between;-->
<!--}-->
<!--.bubble1{-->

<!--  width: 900px;-->
<!--  background: #FFFFFF;-->
<!--  padding: 15px;-->
<!--  margin: 20px 20px 0px 30px;-->
<!--  border-radius: 20px;-->
<!--  height: 60px;-->
<!--  background: #95EC69;-->
<!--  display: flex;-->
<!--  flex-direction: row;-->
<!--  align-content: center;-->
<!--  justify-content: space-between;-->
<!--}-->
<!--</style>-->
